package com.github.baichuan.application.scaffold.rest.domain.authorization;

import com.github.baichuan.application.scaffold.rest.domain.application.Application;
import com.github.baichuan.mapping.EnumDescription;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

import java.util.Comparator;

@Entity
@Getter
@Setter
public class Resource {

    @Id
    private String id;

    @ManyToOne
    @JoinColumn(name = "application_id")
    private Application application;

    private String name;

    private String code;

    @Enumerated(EnumType.STRING)
    private Kind kind;

    private String route;

    private String path;

    private String icon;

    private int sort;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Resource parent;

    @Override
    public boolean equals(Object o){
        if(o == this){
            return true;
        }
        if(o == null){
            return false;
        }
        if(!(o instanceof Resource)){
            return false;
        }
        Resource other = (Resource) o;
        return this.id.equals(other.id);
    }

    /**
     * 检测父资源是否存在循环引用
     * @param resource
     * @return
     */
    public boolean checkCycle(Resource resource){
        for(Resource parent = resource; parent != null; parent = parent.parent){
            if(this.equals(parent)){
                return true;
            }
        }
        return false;
    }

    public enum Kind {
        @EnumDescription("菜单")
        menu,

        @EnumDescription("页面")
        page,

        @EnumDescription("操作")
        action
    }

    public static class SortComparator implements Comparator<Resource> {
        @Override
        public int compare(Resource one, Resource other) {
            if(one.getSort() == other.getSort()){
                return 0;
            }
            else if(one.getSort() < other.getSort()){
                return -1;
            }
            else{
                return 1;
            }
        }
    }
}
